﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BciUtils
{
    public class EegDataWriter : IDisposable
    {
        private StreamWriter infoStream;
        private StreamWriter dateStream;
        private StreamWriter classesStream;

        private Object thisLock = new Object();

        private int lastSampleNumber = 0;

        public EegDataWriter(string filename)
        {
            infoStream = new StreamWriter(filename + EegFileConstants.InfoPostfix);
            dateStream = new StreamWriter(filename + EegFileConstants.DataPostfix);
            classesStream = new StreamWriter(filename + EegFileConstants.LabelsPostfix);
        }

        public void WriteInfo(int channels, int eventChannels, int sampleRate, string[] classes)
        {
            infoStream.WriteLine("Channels:" + channels);
            infoStream.WriteLine("Event Channels:" + eventChannels);
            infoStream.WriteLine("Sample Rate:" + sampleRate);
            infoStream.WriteLine("Classes:" + sampleRate);
            infoStream.Flush();
        }

        public void WriteSamples(List<float[]> samples)
        {
            lock (thisLock)
            {
                foreach (float[] sample in samples)
                {
                    for (int i = 0; i < sample.Length; i++)
                    {
                        float value = sample[i];
                        dateStream.Write(value);

                        if (i < sample.Length - 1)
                        {
                            dateStream.Write(' ');
                        }
                    }

                    dateStream.Write(dateStream.NewLine);                    
                }

                lastSampleNumber += samples.Count;
                dateStream.Flush();
            }
        }

        public void WriteClassLabel(string classLabel)
        {
            classesStream.WriteLine(classLabel + ":" + (lastSampleNumber + 1).ToString());
            classesStream.Flush();
        }

        public void Dispose()
        {
            Close();           
        }

        public void Close()
        {
            infoStream.Close();
            dateStream.Close();
            classesStream.Close();
        }
    }
}
